import { Component, Input, OnInit } from '@angular/core';
import { svg } from 'd3';
import { identity } from 'rxjs';
import { diagram, link, node } from 'src/classes/uielements';
import { CommonService } from 'src/services/common.service';

@Component({
  selector: 'app-design',
  templateUrl: './design.component.html',
  styleUrls: ['./design.component.scss']
})
export class DesignComponent implements OnInit {

  constructor(private commonService: CommonService) { }

  ngOnInit(): void {
    let e = document.getElementById('designer')
    console.log(e.clientWidth);
    console.log(e);
  }
  onDrop(e) {
    let data = e.dragData
    console.log(e);
    if (data.itemtype === 'actor' || 'clue' || 'event' || 'location' || 'group' || 'task' || 'stuff') {
      let id: string = data.item['Id']
      let ids: number[] = []
      this.diagramData.nodes.forEach(v => {
        if (v.id.startsWith(id))
          ids.push((v.id.substring(id.length + 1) as unknown as number))
      })
      if (ids.length > 0) {
        ids.sort()
        id = id + '_' + String(ids[ids.length - 1] + 1)

      } else {
        id = id + '_0'
      }

      this.createnode(id, data.item['Name'], e.nativeEvent.offsetX, e.nativeEvent.offsetY, 120, 80)

    }
  }
  // @Input()
  // public current: Array<node>;
  @Input()
  public diagramData: diagram = new diagram();
  // activelinkpoint = {
  //   active: false,
  //   x: 10,
  //   y: 10
  // }
  activemovelink = false
  // activelinkpointdown(evt) {
  //   this.activemovelink = true
  //   console.log('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
  //   console.log(this.line);
  //   if (this.line !== undefined) {
  //     console.log('ready');
  //     this.line.setAttribute("pointer-events", "none")
  //     //evt.target.setAttribute("pointer-events", "none")
  //   }
  // }
  // activelinkpointup(evt) {
  //   this.activemovelink = false
  // }
  // activelinkpointmove(evt) {
  //   if (this.activemovelink && this.line !== undefined) {
  //     console.log('mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm');
  //     this.line.setAttribute("x2", evt.offsetX);
  //     this.line.setAttribute("y2", evt.offsetY);
  //     this.activelinkpoint.x = evt.offsetX
  //     this.activelinkpoint.y = evt.offsetY
  //   }
  // }
  // testlist = [{
  //   id: 'a',
  //   text: 'xxx',
  //   left: 55,
  //   top: 207,
  //   width: 150,
  //   height: 80,
  //   fill: 'rgb(50, 0, 0)',
  //   active: false
  // },
  // {
  //   id: 'b',
  //   text: 'yyy',
  //   left: 150,
  //   top: 300,
  //   width: 180,
  //   height: 180,
  //   fill: 'rgb(50, 255, 0)',
  //   active: false
  // }]
  //testlink = []
  createlink(x, y, sourceid, sourcetype) {
    // let l = {
    //   startx: x,
    //   starty: y,
    //   endx: x,
    //   endy: y,
    //   sourceid: sourceid,
    //   sourcetype: sourcetype,
    //   targetid: '',
    //   targettype: '',
    //   eventactive: 'none',
    //   id: CommonService.getid('link')
    // }
    // this.testlink.push(l)
    let l = new link()
    l.startX = x
    l.endX = x
    l.startY = y
    l.endY = y
    l.sourceid = sourceid
    l.sourcetype = sourcetype
    l.id = CommonService.getid('link')
    this.diagramData.links.push(l)
    return l
  }
  activelink() {
    console.log(this);
    this.diagramData.links.map(v => v.eventactive = 'auto')
  }
  deactivelink() {
    this.diagramData.links.map(v => v.eventactive = 'none')
  }
  createnode(id, text, x, y, w, h) {
    // let node = {
    //   id: id,

    //   text: text,
    //   left: x,
    //   top: y,
    //   width: 0,
    //   height: 0,
    //   fill: 'rgb(255,255,255)',
    //   active: false
    // }
    // this.diagramData.nodes.push(node)
    // return node
    let n = new node()
    n.id = id
    n.text = text
    n.left = x
    n.top = y
    n.width = w
    n.height = h
    console.log(n);

    this.diagramData.nodes.push(n)
    console.log(this.getDiagramData.nodes);
    return n
  }
  createnew() {
    this.isdrawing = true
  }
  delete() {

    console.log(this.diagramData.nodes);
    let i = this.diagramData.nodes.findIndex(v => v.active)
    console.log(i);
    if (i > -1)
      this.diagramData.nodes.splice(i, 1)
    console.log(this.diagramData.nodes);


  }
  click(item) {
    item.text = 'xxxxxxxxxxxxxxxxxx'
    console.log(item);
  }
  pointScaleR = 3
  pointLinkR = 2
  fillColor = 'rgb(255, 0, 0)';

  isdragging = false//drag node and link line
  isdrawing = false// draw new node

  hit = false
  drawingnode = undefined
  activenode = undefined

  dragstartx = 0
  dragstarty = 0
  basex = 0
  basey = 0
  showLine = false
  currentid = ''
  dbclick(e) {
    console.log('show');
    this.showLine = true
  }
  mousedown(e) {
    console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
    this.isdragging = true
    console.log(e['target']);
    console.log(e['target'].parent);
    let id = e.target['id'].substring(e.target['id'].indexOf('_') + 1)
    let realtarget = document.getElementById(id)
    this.currentid = realtarget["id"]

    //this.testlist.forEach(v => v.active = false)
    let i = this.diagramData.nodes.findIndex(v => v.id === id)
    console.log(id);
    console.log(i);
    this.diagramData.nodes[i].active = !this.diagramData.nodes[i].active
    //this.hit = true
    console.log(this.currentid);
    this.dragstartx = e.offsetX
    this.dragstarty = e.offsetY
    this.basex = Number(realtarget.getAttribute("x"))
    this.basey = Number(realtarget.getAttribute("y"))
    console.log(this.basex);
    e.stopPropagation();
  }

  getLinkPoint(linkpointtype, x, y, w, h) {

    if (linkpointtype === 'l') {
      return [x + 5, y + h / 2 - 5]
    }
    if (linkpointtype === 't') {
      return [x + w / 2 - 5, y + 5]
    }
    if (linkpointtype === 'r') {
      return [x + w - 5, y + h / 2 - 5]
    }
    if (linkpointtype === 'b') {
      return [x + w / 2 - 5, y + h - 5]
    }
  }
  movelink(id, dx, dy) {
    let linklist = document.getElementsByTagName("line")
    let realtarget = document.getElementById(id)

    console.log(dx);
    for (let index = 0; index < linklist.length; index++) {
      const element = linklist[index];
      if (element.getAttribute('sourceid') === id) {
        let linkpoint = this.getLinkPoint(element.getAttribute('sourcetype'), Number(realtarget.getAttribute('x')), Number(realtarget.getAttribute('y')),
          Number(realtarget.getAttribute('width')), Number(realtarget.getAttribute('height')))
        element.setAttribute('x1', linkpoint[0])
        element.setAttribute('y1', linkpoint[1])
      }
      if (element.getAttribute('targetid') === id) {
        let linkpoint = this.getLinkPoint(element.getAttribute('targettype'), Number(realtarget.getAttribute('x')), Number(realtarget.getAttribute('y')),
          Number(realtarget.getAttribute('width')), Number(realtarget.getAttribute('height')))
        element.setAttribute('x2', linkpoint[0])
        element.setAttribute('y2', linkpoint[1])

      }
    }

    for (let index = 0; index < this.diagramData.links.length; index++) {
      const element = this.diagramData.links[index];
      if (element['sourceid'] === id) {
        let linkpoint = this.getLinkPoint(element['sourcetype'], Number(realtarget.getAttribute('x')), Number(realtarget.getAttribute('y')),
          Number(realtarget.getAttribute('width')), Number(realtarget.getAttribute('height')))
        element['startX'] = linkpoint[0]
        element['startY'] = linkpoint[1]
      }
      if (element['targetid'] === id) {
        let linkpoint = this.getLinkPoint(element['targettype'], Number(realtarget.getAttribute('x')), Number(realtarget.getAttribute('y')),
          Number(realtarget.getAttribute('width')), Number(realtarget.getAttribute('height')))
        element['endX'] = linkpoint[0]
        element['endY'] = linkpoint[1]

      }
    }

  }
  mousemove(e) {

    let id = e.target['id'].substring(e.target['id'].indexOf('_') + 1)
    let realtarget = document.getElementById(id)
    //let realtarget = e.target.parent
    if (this.isdragging) {

      //console.log(e);
      // let v=e.target.getAttribute("x")
      // console.log(v);
      let dx = e.offsetX - this.dragstartx
      let dy = e.offsetY - this.dragstarty
      console.log(dx);
      realtarget.setAttribute("x", String(Number(this.basex) + dx));
      realtarget.setAttribute("y", String(Number(this.basey) + dy));

      this.movelink(id, dx, dy)
    }



  }
  mouseup(e) {
    this.isdragging = false
    this.scaling = false
    //this.hit = false
  }
  mouseleave(e) {
    this.isdragging = false
  }
  active(evt) {
    console.log(evt);
    let id = evt.target["id"]
    console.log(id);
  }

  changeColor() {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    this.fillColor = `rgb(${r}, ${g}, ${b})`;

    console.log(document.getElementById('#test')
    )
  }

  linkx = 0
  linky = 0
  line = undefined
  currentline = undefined
  linkmousedown(evt, linktype) {
    if (this.currentline === undefined) {
      let id = evt.target['id'].substring(evt.target['id'].indexOf('_') + 1)
      //this.line = document.createElementNS("http://www.w3.org/2000/svg", "line");
      let realtarget = document.getElementById(id)
      let cx = this.getLinkPoint(linktype, Number(realtarget.getAttribute('x')), Number(realtarget.getAttribute('y')),
        Number(realtarget.getAttribute('width')), Number(realtarget.getAttribute('height')))

      let l = this.createlink(cx[0], cx[1], id, linktype)
      this.currentline = l
      this.deactivelink()
      // this.line.setAttribute("x1", cx[0]);
      // this.line.setAttribute("y1", cx[1]);
      // this.line.setAttribute("x2", cx[0]);
      // this.line.setAttribute("y2", cx[1]);
      // this.line.setAttribute("stroke", 'rgb(0,255,255)')
      // this.line.setAttribute("stroke-width", 5)

      // this.line.setAttribute("sourceid", id)
      // this.line.setAttribute("sourcetype", linktype)
      // this.line.setAttribute("pointer-events", "none")//线不能屏蔽底层的事件响应

      // this.line.setAttribute("marker-end", "url(#arrow)")

      //let svg = document.getElementById('designer')

      // this.line.onclick = "line_click(evt)"
      // this.line.addEventListener("onclick", function () {
      //   console.log('yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy');
      //   this.activelinkpoint.x = evt.target.getAttribute("x1")
      //   this.activelinkpoint.y = evt.target.getAttribute("y1")
      //   this.activelinkpoint.active = true
      //   this.line = evt.target
      // });
      // this.line.addEventListener("onclick", function () {
      //   alert('圆形点击测试：');
      // });

      // this.line.addEventListener("click", function () {
      //   console.log(this);
      //   console.log(this.activelinkpoint);
      // });

      // this.line.addEventListener("mousedown", this.linkclick.bind(this));
      // svg.appendChild(this.line);
      evt.stopPropagation();
    }
  }
  linkclick(e) {
    // console.log(this);
    // console.log(e);
    // this.activelinkpoint.active = true
    // this.activelinkpoint.x = e.target.getAttribute("x2")
    // this.activelinkpoint.y = e.target.getAttribute("y2")
    // this.line = e.target
    // this.line.setAttribute("pointer-events", "none")

    let id = e.target.id
    console.log('link:' + id);
    this.currentline = this.diagramData.links.find(v => v.id === id)
    this.deactivelink()
    e.stopPropagation();
  }
  designermouseup(evt) {
    console.log('designermouseup');

    this.isdrawing = false
    this.drawingnode = undefined
    this.scaling = false
    if (this.line !== undefined)
      this.line.setAttribute("pointer-events", "auto")
    if (!this.activemovelink)
      this.line = undefined
    this.currentline = undefined
    this.activelink()
  }
  designermousedown(evt) {
    console.log('designermousedown!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
    //this.line = undefined

    if (this.isdrawing) {
      this.drawingnode = this.createnode(CommonService.getid('node'), 'test', evt.offsetX, evt.offsetY, 0, 0)
    }
    if (!this.currentline === undefined)
      this.diagramData.nodes.forEach(v => v.active = false)

  }
  linkmouseup(evt, linktype) {
    console.log('linked!!!!!!!!!!!!!!!!');
    // if (this.line !== undefined) {
    //   let id = evt.target['id'].substring(evt.target['id'].indexOf('_') + 1)

    //   let realtarget = document.getElementById(id)
    //   let cx = this.getLinkPoint(linktype, Number(realtarget.getAttribute('x')), Number(realtarget.getAttribute('y')),
    //     Number(realtarget.getAttribute('width')), Number(realtarget.getAttribute('height')))
    //   this.line.setAttribute("targetid", id)
    //   this.line.setAttribute("targettype", linktype)
    //   this.line.setAttribute("x2", cx[0])
    //   this.line.setAttribute("y2", cx[1])
    //   this.line.setAttribute("pointer-events", "auto")
    // }
    if (this.currentline !== undefined) {
      let id = evt.target['id'].substring(evt.target['id'].indexOf('_') + 1)

      let realtarget = document.getElementById(id)
      let cx = this.getLinkPoint(linktype, Number(realtarget.getAttribute('x')), Number(realtarget.getAttribute('y')),
        Number(realtarget.getAttribute('width')), Number(realtarget.getAttribute('height')))
      this.currentline["targetid"] = id
      this.currentline["targettype"] = linktype
      this.currentline["endx"] = cx[0]
      this.currentline["endy"] = cx[1]

    }
    this.activelink()
    this.currentline = undefined
    console.log('linkmouseup');
    //console.log(this.testlink);
    //console.log(this.line);
    evt.stopPropagation();

  }
  designermousemove(evt) {
    if (this.showLine) {
      let h = document.getElementById("hline")
      let v = document.getElementById("vline")

      h.setAttribute("y1", evt.offsetY)
      h.setAttribute("y2", evt.offsetY)
      v.setAttribute("x1", evt.offsetX)
      v.setAttribute("x2", evt.offsetX)
    }
    if (this.line !== undefined) {
      this.line.setAttribute("x2", evt.offsetX);
      this.line.setAttribute("y2", evt.offsetY);

    }
    if (this.currentline !== undefined) {
      this.currentline.endx = evt.offsetX
      this.currentline.endy = evt.offsetY;

    }
    if (this.activemovelink && this.line !== undefined) {
      console.log('mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm');
      this.line.setAttribute("x2", evt.offsetX);
      this.line.setAttribute("y2", evt.offsetY);
      // this.activelinkpoint.x = evt.offsetX
      // this.activelinkpoint.y = evt.offsetY
    }
    if (this.drawingnode !== undefined) {
      console.log(this.drawingnode);
      this.drawingnode.width = Math.abs(evt.offsetX - this.drawingnode.left)
      this.drawingnode.height = Math.abs(evt.offsetY - this.drawingnode.top)
      //this.drawingnode.setAttribute("width", evt.offsetX - this.drawingnode.getAttribute("x"));
      //this.drawingnode.setAttribute("height", evt.offsetY - this.drawingnode.getAttribute("y"));
    }
    if (this.scaling) {
      var data = this.currentscale
      let dx = evt.offsetX - data.left
      let dy = evt.offsetY - data.top
      if (this.scaletype === 'lt') {
        if (dy < data.height) {

          data.height = data.height - dy
          data.top = evt.offsetY
        }
        if (dx < data.width) {

          data.width = data.width - dx
          data.left = evt.offsetX
        }
      }
      if (this.scaletype === 'lb') {
        if (dx < data.width) {

          data.width = data.width - dx
          data.left = evt.offsetX
        }
        if (dy > 0) {
          data.height = dy

        }
      }
      if (this.scaletype === 'rt') {
        if (dy < data.height) {

          data.height = data.height - dy
          data.top = evt.offsetY
        }
        if (dx > 0) {
          data.width = dx

        }
      }
      if (this.scaletype === 'rb') {
        if (dx > 0) {
          data.width = dx

        }
        if (dy > 0) {
          data.height = dy

        }
      }
    }
  }
  llinkmouseleave(evt) {

  }

  getlength(x1, y1, x2, y2) {

  }

  getendpoint(x1, y1, x2, y2, r) {

  }

  scalex = 0
  scaley = 0
  scalel = 0
  scalet = 0
  scaler = 0
  scaleb = 0
  scaling = false

  showActivePoint(w, h, id) {
    let lp = document.getElementById('llink_' + id)
    let tp = document.getElementById('tlink_' + id)
    let rp = document.getElementById('rlink_' + id)
    let bp = document.getElementById('blink_' + id)

    let ltp = document.getElementById('ltscale_' + id)
    let rtp = document.getElementById('rtscale_' + id)
    let lbp = document.getElementById('lbscale_' + id)
    let rbp = document.getElementById('rbscale_' + id)

    lp.setAttribute("cx", String(0));
    lp.setAttribute("cy", String(h / 2 - 3));

    tp.setAttribute("cx", String(w / 2 - 3));
    tp.setAttribute("cy", String(0));

    rp.setAttribute("cx", String(w - 3));
    rp.setAttribute("cy", String(h / 2 - 3));

    bp.setAttribute("cx", String(w / 2 - 3));
    bp.setAttribute("cy", String(h - 3));

    ltp.setAttribute("x", String(0));
    ltp.setAttribute("y", String(0));

    rtp.setAttribute("x", String(w - 3));
    rtp.setAttribute("y", String(0));

    lbp.setAttribute("x", String(0));
    lbp.setAttribute("y", String(h - 3));

    rbp.setAttribute("x", String(w - 3));
    rbp.setAttribute("y", String(h - 3));
  }
  ltscalemousemove(evt) {
    if (this.scaling) {
      let id = evt.target['id'].substring(evt.target['id'].indexOf('_') + 1)
      let realtarget = document.getElementById(id)
      let shapetarget = document.getElementById('shape_' + id)
      let data = this.diagramData.nodes.filter(v => v.id === id)[0]

      //let realtarget = e.target.parent

      // let v=e.target.getAttribute("x")
      // console.log(v);
      let dx = evt.offsetX - this.scalex
      let dy = evt.offsetY - this.scaley

      let l = Number(realtarget.getAttribute("x"))
      let t = Number(realtarget.getAttribute("y"))
      let w = Number(realtarget.getAttribute("width"))
      let h = Number(realtarget.getAttribute("height"))
      let r = l + w
      let b = t + h
      console.log(realtarget);
      console.log(shapetarget);
      console.log(l);
      console.log(t);
      console.log(w);
      console.log(h);
      console.log(this.scalel);
      let nx = evt.offsetX
      let ny = evt.offsetY
      let nw = this.scaler - nx
      let nh = this.scaleb - ny
      console.log(evt);
      console.log(this.scaler);
      console.log(nx);
      console.log(nw);
      let needupdate = false
      if (nw > 0) {
        // data.left = nx

        // data.width = nw
        needupdate = true
        realtarget.setAttribute("x", String(nx - 5));

        shapetarget.setAttribute("width", String(nw));
        realtarget.setAttribute("width", String(nw + 10));
      }
      if (nh > 0) {
        // data.top = ny
        // data.height = nh
        needupdate = true
        realtarget.setAttribute("y", String(ny - 5));

        shapetarget.setAttribute("height", String(nh));
        realtarget.setAttribute("height", String(nh + 10));
      }
      // if (needupdate)
      //   this.showActivePoint(nw, nh, id)
    }
  }
  ltscalemouseleave(evt) {

    //this.scaling = false

  }
  scaletype = ''
  currentscale = undefined
  scalemousedown(evt, scaletype) {
    let id = evt.target['id'].substring(evt.target['id'].indexOf('_') + 1)
    let realtarget = document.getElementById(id)
    this.scalex = Number(evt.offsetX - Number(realtarget.getAttribute("x")))
    this.scaley = Number(evt.offsetY - Number(realtarget.getAttribute("y")))

    this.scalel = Number(realtarget.getAttribute("x"))
    this.scalet = Number(realtarget.getAttribute("y"))
    this.scaler = Number(realtarget.getAttribute("x")) + Number(realtarget.getAttribute("width"))
    this.scaleb = Number(realtarget.getAttribute("y")) + Number(realtarget.getAttribute("height"))

    this.scaling = true
    this.scaletype = scaletype

    let data = this.diagramData.nodes.find(v => v.id === id)
    this.currentscale = data
    evt.stopPropagation();
  }
  ltscalemouseup(evt) {
    this.scaling = false
  }
  scalemousemove(evt, scaletype) {
    if (this.scaling) {

      let id = evt.target['id'].substring(evt.target['id'].indexOf('_') + 1)
      let data = this.diagramData.nodes.find(v => v.id === id)
      console.log(evt);
      if (scaletype === 'lt') {
        if (evt.offsetX < data.left + data.width) {

          data.width = data.left + data.width - evt.offsetX
          data.left = evt.offsetX
        }
        if (evt.offsetY < data.top + data.height) {

          data.height = data.top + data.height - evt.offsetY
          data.top = evt.offsetY
        }
      }
      //let realtarget = e.target.parent

      // let v=e.target.getAttribute("x")
      // console.log(v);

    }
    evt.stopPropagation();
  }
  public get getDiagramData() {
    if (this.diagramData === undefined) {
      this.diagramData = new diagram()

    }

    console.log(this.diagramData);
    return this.diagramData
  }



  output() {
    console.log(this.getDiagramData.nodes);
  }
  create() {
    this.createnode('sssssssss', 'xxxxxxxxxxxxx', 100, 100, 100, 100)
  }

}
